<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\Admins;
use app\api\model\v1\AuthRule;
use app\api\validate\v1\MenuValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\Request;

class Menu extends BaseController
{

    use SearchDataForModel;

    /**
     * @User: 刘海龙
     * @Date: 2021/9/22
     * @Time: 17:57
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取菜单数据列表
     */
    public function menuInfo(){

        $data = AuthRule::select();
        $name = $this->request->param('name', '');
        $type = $this->request->param('type', 'list');

        if (!empty($name) && $type == 'child') {
            $top = AuthRule::where('pid', 0)
                ->where('title', 'like', '%' . $name . '%')
                ->order('sort', 'asc')->select()->toArray();
        }
        if (!empty($top) && $type == 'child') {
            $res       = [];
            $parent_id = [];
            foreach ($top as $key => $val) {
                $res[]              = $val;
                $res[$key]['child'] = AuthRule::sortMenu($data, $val['id']);
                $parent_id[]        = $val['id'];
            }
            empty($name) ?:
                $down = AuthRule::whereNotIn('pid', $parent_id)
                    ->where('name', 'like', '%' . $name . '%')
                    ->order('sort', 'asc')->where('pid', '<>', 0)
                    ->select()->toArray();
            empty($down) ?: $res = array_merge($res, $down);
        } elseif (empty($name) && $type == 'child') {
            $data = $this->search(new AuthRule(), [], $perPage = 200);
            $res  = AuthRule::sortMenu($data, 0);
        } else {
            $res = $this->search(new AuthRule(), [], $perPage = 200);
        }
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/22
     * @Time: 17:51
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 菜单权限
     */
    public function menuPermission()
    {
        $user = Admins::find($this->request->uid);
        // 检查用户权限
        $role_ids = array_column($user->roles()->select()->toArray(),
            'rules');//获取该用户所属角色rules
        if (in_array('*', $role_ids)) {
            $data = AuthRule::field('id,pid,name,title,status,sort,icon,is_menu')->where(['is_menu' => AuthRule::IS_MENU_ONE, 'status' => 1])->order('id asc')->select()
                ->toArray();
        } else {
            $data = AuthRule::field('id,pid,name,title,status,sort,icon,is_menu')->where('id', 'in', implode(',', $role_ids))
                ->where(['is_menu' => AuthRule::IS_MENU_ONE, 'status' => 1])->order('id asc')
                ->select()->toArray();
        }
        $res = AuthRule::sortMenu($data);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/23
     * @Time: 14:33
     * @return \think\response\Json
     * 菜单类别
     */
    public function MenuType()
    {
        $content = [
            [
                'id' => AuthRule::TYPE_ONE,
                'name' => AuthRule::$is_type[AuthRule::TYPE_ONE],
            ],
            [
                'id' => AuthRule::TYPE_TWO,
                'name' => AuthRule::$is_type[AuthRule::TYPE_TWO],

            ],
        ];
        return $this->response($content);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/22
     * @Time: 10:21
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存or编辑菜单
     */
    public function saveMenu()
    {
        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                MenuValidate::rules($id),
                MenuValidate::msg());
            if ($validator) {
                $data = $this->request->param();
                $data['is_open'] = $this->request->param('status', true) ? AuthRule::OPEN_ONE : AuthRule::OPEN_TWO;
                $parent_id = $this->request->param('pid', 0);
                if (intval($parent_id) === 0) {
                    $data['level'] = 0;
                } else {
                    $data['level'] = AuthRule::find($parent_id)->level + 1;
                }
                $data['pid'] = $parent_id;
                if (intval($id) === 0) {
                    if (intval($parent_id) != 0) {
                        if (AuthRule::find($parent_id)->level === 2) {
                            return $this->response(501, "菜单只能添加3级");
                        }
                    }
                    AuthRule::create($data);
                } else {
                    $menu = AuthRule::find($id);
                    $menu->save($data);
                }
                //日志
                AdminLog::record(intval($id) === 0 ? '新增菜单' : '编辑菜单', $this->request->param(), $this->request->uid, $this->request->username);
                return $this->response();
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/22
     * @Time: 17:37
     * @return \think\response\Json
     * 删除
     */
    public function delMenu()
    {
        $ids = $this->request->param('ids');
        if (empty($ids)) {
            return $this->response(403, "请选择删除菜单");
        }
        $arr_ids = explode(',', $ids);
        AuthRule::destroy($arr_ids);
        //日志
        AdminLog::record('删除菜单', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }
}
